function fsl_measure()
% basic template file for data analysis routines.
% gets the current datac window selection, and does the analysis
% for all selected record groups/blocks
% automatically refreshes the data arrays from the disk file if necessary
% and also shows how to generate a figure.
% 8/23/05 P. Manis

% the main routine is just a wrapper to handle the multiple selection and
% catch execution errors.
%
% Note: when testing, set the testflag to 1 so that we DO NOT do try/catch.
% you need to do this to catch the errors in the _go routine.
%
global CONTROL
sf = getmainselection; % read the list of selected traces
testflag = 1;

if(sf > 0)
    pflag = getplotflag; % read teh plot flag (used in the routine template2)
    hf = fopen('/users/pmanis/desktop/fsl.txt', 'w');
    
    QueMessage('First spike latency measurement', 1); % clear the que
    fprintf(1, '\nFile    FSL  FSLSD   N   Nspike   NSPmin  NSPmax\n');
    fprintf(hf, '\nFile    FSL  FSLSD   N   Nspike   NSPmin  NSPmax\n');
    for i = 1:length(sf)
        if(testflag == 0)
            try
                template_go(sf(i), pflag, hf);
            catch
                fprintf(1, 'FSL Failed execution for sf = %d\n  ***[File: %s, records: %d - %d ]\n', ...
                    sf(i), CONTROL(sf(i)).filename, CONTROL(sf(i)).recbeg, CONTROL(sf(i)).recend);
            end;
        else
            template_go(sf(i), 0, hf); % also turn off plot flag when testing
        end;

    end;
    fclose(hf);
    
end;



%--------------The real analysis routine------------------

function template_go(sf, pflag, hf)

% access to all of the data and parameters
global DFILE ALLCH VOLTAGE CONTROL

% set some control parameters
isrc = 1;
t0 = 0;
tmax = 1000;
spike_thresh = 0;

% this next routine reads all of the data and information we need,
% including calculating some standard stuff that is put into DPAR.
% you will want DPAR.time especially - it is the time base that goes
% with the data.

[DFILE, DPAR, err] = ana_setup(DFILE, sf);
if(err ~= 0)
    return;
end;

if(~isempty(ALLCH))
    VOLTAGE = ALLCH{isrc};
    CURRENT = ALLCH{isrc+1};
end;


% the analysis here is just finding spikes
t0 = CONTROL(sf).durho;
tmax = (CONTROL(sf).durho + CONTROL(sf).durs1);
[first_spike, first_isi, nr_spikes, splat, peaklat]=find_spikes2(DFILE, VOLTAGE, t0, tmax, DPAR.spike_thresh);
[mlat, vlat, n] = mean_var([peaklat]);
fprintf(1, '%s, %7.4f, %7.4f, %d, %.2f, %d, %d\n', DFILE.filename, mlat, vlat, n, mean(nr_spikes), min(nr_spikes), max(nr_spikes));
fprintf(hf, '%s, %7.4f, %7.4f, %d, %.2f, %d, %d\n', DFILE.filename, mlat, vlat, n, mean(nr_spikes), min(nr_spikes), max(nr_spikes));





